﻿using System;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json;
using ZilLion.Service.Core.Unities.UnitiesMethods;

namespace ZilLion.Service.TaskPlatform.Domain.ErrorReporter
{
    public class QyWechatHelper
    {
        private static DateTime _nextExpTime = DateTime.Now;
        private static  string _token = string.Empty;

        public static void SendMessage(string[] sendTargets, string msg)
        {
            if (_token.IsNullOrEmpty() || _nextExpTime < DateTime.Now.AddMinutes(-20))
                RefreshQyWechatToken();

            var url = $"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={_token}";
            var users = sendTargets.Aggregate(string.Empty, (current, send) => current + send + "|")
                .ReplaceLast("|", string.Empty);

            var request = new QyWechatTextMessageRequest
            {
                touser = users,
                msgtype = "text",
                text = new Text {content = msg},
                safe = 0,
                agentid = 1000009
            };
            HttpContent httpContent = null;
            httpContent = new StringContent(JsonConvert.SerializeObject(request));
            httpContent.Headers.ContentType.MediaType = "application/json";
            httpContent.Headers.ContentType.CharSet = "utf-8";
         var res=   HttpHelper.HttpRequestPost<QyWechatTextMessageResponse>(url, httpContent);
            Console.WriteLine(JsonConvert.SerializeObject(res));
        }

        private static void RefreshQyWechatToken()
        {
            var tokenresponse = HttpHelper.HttpRequestGet<QyWechatTokenResponse>(
                $"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wx83963c6876632e29&corpsecret=JViIbfDlVNk99zhQVu4Yp1winyw2-qDZbAnYprJlQfU");

            if (tokenresponse != null && tokenresponse.Errcode == 0)
            {
                _nextExpTime = DateTime.UtcNow.AddHours(8).AddSeconds(tokenresponse.ExpiresIn);
                _token = tokenresponse.AccessToken;
            }
       
        }
    }
}